package com.leyou.upload.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.config.UploadProperties;
import com.leyou.upload.service.IUpLoadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
@EnableConfigurationProperties(UploadProperties.class)
public class UploadServiceImpl implements IUpLoadService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private UploadProperties prop;


    @Override
    public String uploadImage(MultipartFile file) {
        try {
            String fileContentType = file.getContentType();

            if (!prop.getAllowTypes().contains(fileContentType)) {
                log.info("上传失败,文件类型不匹配: {}",fileContentType);
                throw new LyException(ExceptionEnum.FILE_TYPE_NOT_MATCH);
            }

            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                log.info("上传失败,文件内容不符合要求");
                throw new LyException(ExceptionEnum.FILE_CONTEXT_NOT_MATCH);
            }

            String fileEtname = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), fileEtname, null);

            return prop.getBaseUrl()+storePath.getFullPath();
        } catch (Exception e) {
            // 上传失败
            log.error("[文件上传] 上传文件失败!", e);
            throw new LyException(ExceptionEnum.FILE_UPLOAD_EXCEPTION);
        }
    }
}
